import EXIF from 'exif-js'
import { arrayHadArrayVal } from "_commonFn/array"

// 图片压缩上传，返回链接
class ImageCompress {
    constructor() {
        // 创建绘图
        if (document.getElementById('image-compress-canvas')) {
            const canvas = document.getElementById('image-compress-canvas'),
            ctx = canvas.getContext('2d');
            this.canvas = canvas;
            this.ctx = ctx;
        } else {
            const canvas = document.createElement("canvas"),
            ctx = canvas.getContext('2d');
            document.body.appendChild(canvas);
            canvas.className='disnone';
            canvas.id = 'image-compress-canvas'
            this.canvas = canvas;
            this.ctx = ctx;
        }
    }

    //图片压缩
    compress(file) {
        const _this = this;
        // console.log('file',file)
        const reader = new FileReader(),
            image = new Image();
        var Orientation = null;
        return new Promise((resolve, reject) => {
            reader.onload = function (ev) {
                EXIF.getData(file, function () {
                    Orientation = EXIF.getTag(this, 'Orientation');
                });
                image.src = ev.target.result;
                image.onload = function () {
                    var imgWidth = this.width,
                        imgHeight = this.height;
                    _this.canvas.width = imgWidth;
                    _this.canvas.height = imgHeight;
                    if (Orientation && Orientation != 1) {
                        switch (Orientation) {
                            case 6:     // 旋转90度
                                _this.canvas.width = imgHeight;
                                _this.canvas.height = imgWidth;
                                _this.ctx.rotate(Math.PI / 2);
                                // (0,-imgHeight) 从旋转原理图那里获得的起始点
                                _this.ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight);
                                break;
                            case 3:     // 旋转180度
                                _this.ctx.rotate(Math.PI);
                                _this.ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight);
                                break;
                            case 8:     // 旋转-90度
                                _this.canvas.width = imgHeight;
                                _this.canvas.height = imgWidth;
                                _this.ctx.rotate(3 * Math.PI / 2);
                                _this.ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight);
                                break;
                        }
                    } else {
                        _this.ctx.drawImage(this, 0, 0, imgWidth, imgHeight)
                    }
                    // 大于1M质量为原来的X 小于1M质量为原来的Y
                    const compressibility = file.size > 1024000 ? 0.2 : 0.8
                    const imgDta = _this.canvas.toDataURL("image/jpeg", compressibility)
                    resolve(imgDta)
                }
            }
            reader.readAsDataURL(file)
        })
    }
}

// 不对图片进行压缩，直接转成base64
function directTurnIntoBase64(fileObj) {
    var r = new FileReader()
    return new Promise(resolve => {
        // 转成base64
        r.onload = function () {
            //变成字符串  
            const imgBase64 = r.result
            resolve(imgBase64)
        }
        r.readAsDataURL(fileObj)  //转成Base64格式
    })
}

// Base64 to Blob
function dataURLtoBlob(dataUrl) {
    var arr = dataUrl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

// 检测是否为预览的图片
export const checkIsPreviewImg = (e, callback) => {
    const imgName = ['img', 'IMG']
    let imgSrc = false
    if (e && e.target && imgName.includes(e.target.tagName) && e.target.tagName) {
        // console.log('e', e)
        if (e.target.classList && e.target.classList.length > 0) {
            const classList = Array.from(e.target.classList)
            if (arrayHadArrayVal({
                arrayMain: process.env.IMG_PREVIEW_CLASS_LIST,
                array: classList
            })) {
                imgSrc = e.target.src || e.target.currentSrc || false
            }
        }
    }
    typeof callback === 'function' && callback(imgSrc)
}

export { ImageCompress, dataURLtoBlob, directTurnIntoBase64 }